/////////////////////////////////////////////////////////////////////////////
// Name:        tts_htmlparser.cpp
// Purpose:     Simple HTML parser
// Author:      Julian Smart
// Modified by:
// Created:     2002-09-25
// RCS-ID:      $Id: htmlparser.cpp,v 1.2 2006/12/14 04:19:24 anthemion Exp $
// Copyright:   (c) Julian Smart
// Licence:     New BSD License
/////////////////////////////////////////////////////////////////////////////

// ----------------------------------------------------------------------------
// headers
// ----------------------------------------------------------------------------
#include "tts/tts_pch.h"

#include "wx/textfile.h"
#include "wx/wfstream.h"

#include <ctype.h>

#include "tts/tts_htmlparser.h"

/// Useful insertion operators for wxOutputStream.
static wxOutputStream& operator <<(wxOutputStream& stream, const wxString& s)
{
    stream.Write(s, s.Length());
    return stream;
}

/*
 * wxTTSSimpleHtmlAttribute
 * Representation of an attribute
 */

wxTTSSimpleHtmlParser::wxTTSSimpleHtmlParser()
{
    m_topLevel = NULL;
    m_pos = 0;
}


wxTTSSimpleHtmlParser::~wxTTSSimpleHtmlParser()
{
    Clear();
}

bool wxTTSSimpleHtmlParser::ParseFile(const wxString& filename, const wxString& encoding)
{
    bool success = false;
    wxTextFile textFile;

    wxMBConv* conv = NULL;
    if (encoding.IsEmpty())
        conv = & wxConvUTF8;
    else
        conv = new wxCSConv(encoding);

    if (textFile.Open(filename, * conv))
    {
        wxString text;
        wxString line;
        int i;
        int count = textFile.GetLineCount();
        for (i = 0; i < count; i++)
        {
            if (i == 0)
                line = textFile.GetFirstLine();
            else
                line = textFile.GetNextLine();

            text += line;
            if (i != (count - 1))
                text += wxT("\n");
        }

#if 0
        for ( line = textFile.GetFirstLine(); !textFile.Eof(); line = textFile.GetNextLine() )
        {
            text += line;
            if (!textFile.Eof())
                text += wxT("\n");
        }
#endif

        success = ParseString(text);
    }
    else
        success = false;
    if (!encoding.IsEmpty())
        delete conv;
    return success;
}

bool wxTTSSimpleHtmlParser::ParseString(const wxString& str)
{
    Clear();

    m_pos = 0;
    m_text = str;
    m_length = str.Length();

    m_topLevel = new wxTTSSimpleHtmlTag(wxT("TOPLEVEL"), wxTTSSimpleHtmlTag_TopLevel);

    return ParseHtml(m_topLevel);
}

// Main recursive parsing function
bool wxTTSSimpleHtmlParser::ParseHtml(wxTTSSimpleHtmlTag* parent)
{
    while (!Eof())
    {
        EatWhitespace();
        if (IsComment())
        {
            ParseComment();
        }
        else if (IsDirective())
        {
            wxTTSSimpleHtmlTag* tag = ParseDirective();
            if (tag)
                parent->AppendTag(tag);
        }
        else if (IsTagClose())
        {
            wxTTSSimpleHtmlTag* tag = ParseTagClose();
            if (tag)
                parent->AppendTag(tag);
        }
        else if (IsTagStartBracket(GetChar(m_pos)))
        {
            wxTTSSimpleHtmlTag* tag = ParseTagHeader();
            if (tag)
                parent->AppendTag(tag);
        }
        else if (GetChar(m_pos) == wxT('&'))
        {
            wxString entity;
            m_pos ++;
            while (!Eof(m_pos) && GetChar(m_pos) != wxT(';'))
            {
                entity += GetChar(m_pos);
                m_pos ++;
            }
            if (!Eof(m_pos))
                m_pos ++;

            wxTTSSimpleHtmlTag* tag = new wxTTSSimpleHtmlTag(entity, wxTTSSimpleHtmlTag_Entity);
            parent->AppendTag(tag);
        }
        else
        {
            // Just a text string
            wxString text;
            ParseText(text);

            wxTTSSimpleHtmlTag* tag = new wxTTSSimpleHtmlTag(wxT("TEXT"), wxTTSSimpleHtmlTag_Text);
            tag->SetText(text);
            parent->AppendTag(tag);
        }
    }
    return TRUE;
}

// Plain text, up until an angled bracket
bool wxTTSSimpleHtmlParser::ParseText(wxString& text)
{
    while (!Eof() && GetChar(m_pos) != wxT('<') && GetChar(m_pos) != wxT('&'))
    {
        text += GetChar(m_pos);
        m_pos ++;
    }
    return TRUE;
}

wxTTSSimpleHtmlTag* wxTTSSimpleHtmlParser::ParseTagHeader()
{
    if (IsTagStartBracket(GetChar(m_pos)))
    {
        m_pos ++;
        EatWhitespace();

        wxString word;
        ReadWord(word, TRUE);

        EatWhitespace();

        wxTTSSimpleHtmlTag* tag = new wxTTSSimpleHtmlTag(word, wxTTSSimpleHtmlTag_Open);

        ParseAttributes(tag);

        EatWhitespace();

        if (IsTagEndBracket(GetChar(m_pos)))
            m_pos ++;

        return tag;
    }
    else
        return NULL;
}

wxTTSSimpleHtmlTag* wxTTSSimpleHtmlParser::ParseTagClose()
{
    Matches(wxT("</"), TRUE);

    EatWhitespace();

    wxString word;
    ReadWord(word, TRUE);

    EatWhitespace();
    m_pos ++;

    wxTTSSimpleHtmlTag* tag = new wxTTSSimpleHtmlTag(word, wxTTSSimpleHtmlTag_Close);
    return tag;
}

bool wxTTSSimpleHtmlParser::ParseAttributes(wxTTSSimpleHtmlTag* tag)
{
    // Parse attributes of a tag header until we reach >
    while (!IsTagEndBracket(GetChar(m_pos)) && !Eof())
    {
        EatWhitespace();

        wxString attrName, attrValue;

        if (IsString())
        {
            ReadString(attrName, TRUE);
            tag->AppendAttribute(attrName, wxEmptyString);
        }
        else if (IsNumeric(GetChar(m_pos)))
        {
            ReadNumber(attrName, TRUE);
            tag->AppendAttribute(attrName, wxEmptyString);
        }
        else
        {
            // Try to read an attribute name/value pair, or at least a name
            // without the value
            ReadLiteral(attrName, TRUE);
            EatWhitespace();

            if (GetChar(m_pos) == wxT('='))
            {
                m_pos ++;
                EatWhitespace();

                if (IsString())
                    ReadString(attrValue, TRUE);
                else if (!Eof() && !IsTagEndBracket(GetChar(m_pos)))
                    ReadLiteral(attrValue, TRUE);
            }
            if (!attrName.IsEmpty())
                tag->AppendAttribute(attrName, attrValue);
        }
    }
    return TRUE;
}

// e.g. <!DOCTYPE ....>
wxTTSSimpleHtmlTag* wxTTSSimpleHtmlParser::ParseDirective()
{
    Matches(wxT("<!"), TRUE);

    EatWhitespace();

    wxString word;
    ReadWord(word, TRUE);

    EatWhitespace();

    wxTTSSimpleHtmlTag* tag = new wxTTSSimpleHtmlTag(word, wxTTSSimpleHtmlTag_Directive);

    ParseAttributes(tag);

    EatWhitespace();

    if (IsTagEndBracket(GetChar(m_pos)))
        m_pos ++;

    return tag;
}

bool wxTTSSimpleHtmlParser::ParseComment()
{
    // Eat the comment tag start
    Matches(wxT("<!--"), TRUE);

    while (!Eof() && !Matches(wxT("-->"), TRUE))
    {
        m_pos ++;
    }

    return TRUE;
}

bool wxTTSSimpleHtmlParser::EatWhitespace()
{
    while (!Eof() && IsWhitespace(GetChar(m_pos)))
        m_pos ++;
    return TRUE;
}

bool wxTTSSimpleHtmlParser::EatWhitespace(int& pos)
{
    while (!Eof(pos) && IsWhitespace(GetChar(pos)))
        pos ++;
    return TRUE;
}

bool wxTTSSimpleHtmlParser::ReadString(wxString& str, bool eatIt)
{
    int pos = m_pos;
    if (GetChar(pos) == (int) '"')
    {
        pos ++;
        while (!Eof(pos) && GetChar(pos) != (int) '"')
        {
            // TODO: how are quotes escaped in HTML?
            str += (wxChar) GetChar(pos);
            pos ++;
        }
        if (GetChar(pos) == (int) '"')
            pos ++;
        if (eatIt)
            m_pos = pos;
        return TRUE;
    }
    else
        return FALSE;
}

bool wxTTSSimpleHtmlParser::ReadWord(wxString& str, bool eatIt)
{
    int pos = m_pos;

    if (!IsAlpha(GetChar(pos)) && GetChar(pos) != wxT(':'))
        return FALSE;

    str += (wxChar) GetChar(pos) ;
    pos ++;

    while (!Eof(pos) && (GetChar(pos) == wxT(':') || IsWordChar(GetChar(pos))))
    {
        str += (wxChar) GetChar(pos);
        pos ++;
    }
    if (eatIt)
        m_pos = pos;
    return TRUE;
}

bool wxTTSSimpleHtmlParser::ReadNumber(wxString& str, bool eatIt)
{
    int pos = m_pos;

    if (!IsNumeric(GetChar(pos)))
        return FALSE;

    str += (wxChar) GetChar(pos) ;
    pos ++;

    while (!Eof(pos) && IsNumeric(GetChar(pos)))
    {
        str += (wxChar) GetChar(pos);
        pos ++;
    }
    if (eatIt)
        m_pos = pos;
    return TRUE;
}

// Could be number, string, whatever, but read up until whitespace or end of tag (but not a quoted string)
bool wxTTSSimpleHtmlParser::ReadLiteral(wxString& str, bool eatIt)
{
    int pos = m_pos;

    while (!Eof(pos) && !IsWhitespace(GetChar(pos)) && !IsTagEndBracket(GetChar(pos)) && GetChar(pos) != wxT('='))
    {
        str += GetChar(pos);
        pos ++;
    }
    if (eatIt)
        m_pos = pos;
    return TRUE;
}

bool wxTTSSimpleHtmlParser::IsTagClose()
{
    return Matches(wxT("</"));
}

bool wxTTSSimpleHtmlParser::IsComment()
{
    return Matches(wxT("<!--"));
}

bool wxTTSSimpleHtmlParser::IsDirective()
{
    return Matches(wxT("<!"));
}

bool wxTTSSimpleHtmlParser::IsString()
{
    return (GetChar(m_pos) == (int) '"') ;
}

bool wxTTSSimpleHtmlParser::IsWord()
{
    return (IsAlpha(GetChar(m_pos)));
}

bool wxTTSSimpleHtmlParser::IsTagStartBracket(int ch)
{
    return (ch == wxT('<'));
}

bool wxTTSSimpleHtmlParser::IsTagEndBracket(int ch)
{
    return (ch == wxT('>'));
}

bool wxTTSSimpleHtmlParser::IsWhitespace(int ch)
{
    return ((ch == 13) || (ch == 10) || (ch == 32) || (ch == (int) '\t')) ;
}

bool wxTTSSimpleHtmlParser::IsAlpha(int ch)
{
    return (wxIsalpha((wxChar) ch) != 0);
}

bool wxTTSSimpleHtmlParser::IsWordChar(int ch)
{
    return (wxIsalpha((wxChar) ch) != 0 || ch == wxT('-') || ch == wxT('_') || IsNumeric(ch));
}

bool wxTTSSimpleHtmlParser::IsNumeric(int ch)
{
    return (wxIsdigit((wxChar) ch) != 0 || ch == wxT('-') || ch == wxT('.')) ;
}

// Matches this string (case insensitive)
bool wxTTSSimpleHtmlParser::Matches(const wxString& tok, bool eatIt)
{
    wxString text(m_text.Mid(m_pos, tok.Length()));
    bool success = (text.CmpNoCase(tok) == 0) ;
    if (success && eatIt)
    {
        m_pos += tok.Length();
    }
    return success;
}

// Safe way of getting a character
int wxTTSSimpleHtmlParser::GetChar(size_t i) const
{
    if (i >= (size_t) m_length)
        return -1;
    return m_text[i];
}

void wxTTSSimpleHtmlParser::Clear()
{
    if (m_topLevel)
        delete m_topLevel;
    m_topLevel = NULL;
    m_text = wxEmptyString;
    m_pos = 0;
    m_length = 0;
}

// Write this file
void wxTTSSimpleHtmlParser::Write(wxOutputStream& stream)
{
    if (m_topLevel)
        m_topLevel->Write(stream);
}

bool wxTTSSimpleHtmlParser::WriteFile(wxString& filename)
{
    wxFileOutputStream fstream(filename);
    if (fstream.Ok())
    {
        Write(fstream);
        return TRUE;
    }
    else
        return FALSE;
}

/*
 * wxTTSSimpleHtmlTag
 * Representation of a tag or chunk of text
 */

wxTTSSimpleHtmlTag::wxTTSSimpleHtmlTag(const wxString& tagName, int tagType)
{
    m_name = tagName;
    m_type = tagType;
    m_attributes = NULL;
    m_children = NULL;
    m_parent = NULL;
    m_next = NULL;
}

wxTTSSimpleHtmlTag::~wxTTSSimpleHtmlTag()
{
    ClearAttributes();
    ClearChildren();
}

//// Operations
void wxTTSSimpleHtmlTag::ClearAttributes()
{
    if (m_attributes)
    {
        wxTTSSimpleHtmlAttribute* attr = m_attributes;
        while (attr)
        {
            wxTTSSimpleHtmlAttribute* next = attr->m_next;

            attr->m_next = NULL;
            delete attr;
            attr = next;
        }
        m_attributes = NULL;
    }
}

wxTTSSimpleHtmlAttribute* wxTTSSimpleHtmlTag::FindAttribute(const wxString& name) const
{
    wxTTSSimpleHtmlAttribute* attr = m_attributes;
    while (attr)
    {
        if (attr->GetName().CmpNoCase(name) == 0)
        {
            return attr;
        }
        attr = attr->m_next;
    }
    return NULL;
}

void wxTTSSimpleHtmlTag::AppendAttribute(const wxString& name, const wxString& value)
{
    wxTTSSimpleHtmlAttribute* attr = new wxTTSSimpleHtmlAttribute(name, value);
    if (m_attributes)
    {
        // Find tail
        wxTTSSimpleHtmlAttribute* last = m_attributes;
        while (last->m_next)
            last = last->m_next;

        last->m_next = attr;
    }
    else
        m_attributes = attr;
}

void wxTTSSimpleHtmlTag::ClearChildren()
{
    if (m_children)
    {
        wxTTSSimpleHtmlTag* child = m_children;
        while (child)
        {
            wxTTSSimpleHtmlTag* next = child->m_next;

            child->m_next = NULL;
            delete child;
            child = next;
        }
        m_children = NULL;
    }
}

void wxTTSSimpleHtmlTag::AppendTag(wxTTSSimpleHtmlTag* tag)
{
    if (m_children)
    {
        // Find tail
        wxTTSSimpleHtmlTag* last = m_children;
        while (last->m_next)
            last = last->m_next;

        last->m_next = tag;
        tag->m_parent = this;
    }
    else
        m_children = tag;
}

// Gets the text from this tag and its descendants
wxString wxTTSSimpleHtmlTag::GetTagText()
{
    wxString text;
    if (m_children)
    {
        wxTTSSimpleHtmlTag* tag = m_children;
        while (tag)
        {
            text += tag->GetTagText();
            tag = tag->m_next;
        }
        return text;
    }
    else if (GetType() == wxTTSSimpleHtmlTag_Text)
        return GetText();
    else
        return wxEmptyString;
}

int wxTTSSimpleHtmlTag::GetAttributeCount() const
{
    int count = 0;
    wxTTSSimpleHtmlAttribute* attr = m_attributes;
    while (attr)
    {
        count ++;
        attr = attr->m_next;
    }
    return count;
}

wxTTSSimpleHtmlAttribute* wxTTSSimpleHtmlTag::GetAttribute(int i) const
{
    int count = 0;
    wxTTSSimpleHtmlAttribute* attr = m_attributes;
    while (attr)
    {
        if (count == i)
            return attr;
        count ++;
        attr = attr->m_next;
    }
    return NULL;
}

int wxTTSSimpleHtmlTag::GetChildCount() const
{
    int count = 0;
    wxTTSSimpleHtmlTag* tag = m_children;
    while (tag)
    {
        count ++;
        tag = tag->m_next;
    }
    return count;
}

bool wxTTSSimpleHtmlTag::HasAttribute(const wxString& name, const wxString& value) const
{
    wxTTSSimpleHtmlAttribute* attr = FindAttribute(name);

    return (attr && (attr->GetValue().CmpNoCase(value) == 0)) ;
}

bool wxTTSSimpleHtmlTag::HasAttribute(const wxString& name) const
{
    return FindAttribute(name) != NULL ;
}

bool wxTTSSimpleHtmlTag::GetAttributeValue(wxString& value, const wxString& attrName)
{
    wxTTSSimpleHtmlAttribute* attr = FindAttribute(attrName);
    if (attr)
    {
        value = attr->GetValue();
        return TRUE;
    }
    else
        return FALSE;
}

// Search forward from this tag until we find a tag with this name & attribute 
wxTTSSimpleHtmlTag* wxTTSSimpleHtmlTag::FindTag(const wxString& tagName, const wxString& attrName)
{
    wxTTSSimpleHtmlTag* tag = m_next;
    while (tag)
    {
        if (tag->NameIs(tagName) && (attrName.IsEmpty() || tag->FindAttribute(attrName)))
            return tag;

        tag = tag->m_next;
    }
    return NULL;
}

bool wxTTSSimpleHtmlTag::FindTextUntilTagClose(wxString& text, const wxString& tagName)
{
    wxTTSSimpleHtmlTag* tag = this;
    while (tag)
    {
        if (tag->GetType() == wxTTSSimpleHtmlTag_Close && tag->NameIs(tagName))
            return TRUE;

        if (tag->GetType() == wxTTSSimpleHtmlTag_Text)
            text += tag->GetText();

        tag = tag->m_next;
    }
    return TRUE;
}


wxTTSSimpleHtmlTag* wxTTSSimpleHtmlTag::GetChild(int i) const
{
    int count = 0;
    wxTTSSimpleHtmlTag* tag = m_children;
    while (tag)
    {
        if (count == i)
            return tag;

        count ++;
        tag = tag->m_next;
    }
    return NULL;
}

void wxTTSSimpleHtmlTag::Write(wxOutputStream& stream)
{
    switch (GetType())
    {
    case wxTTSSimpleHtmlTag_Text:
        {
            stream << m_text;
            break;
        }
    case wxTTSSimpleHtmlTag_Open:
        {
            stream << wxT("<") << m_name;
            if (GetAttributeCount() > 0)
                stream << wxT(" ");
            int i;
            for (i = 0; i < GetAttributeCount(); i++)
            {
                wxTTSSimpleHtmlAttribute* attr = GetAttribute(i);
                attr->Write(stream);
                if (i < GetAttributeCount() - 1)
                    stream << wxT(" ");
            }
            stream << wxT(">\n");
            break;
        }
    case wxTTSSimpleHtmlTag_Directive:
        {
            stream << wxT("<!") << m_name << wxT(" ");
            int i;
            for (i = 0; i < GetAttributeCount(); i++)
            {
                wxTTSSimpleHtmlAttribute* attr = GetAttribute(i);
                attr->Write(stream);
                if (i < GetAttributeCount() - 1)
                    stream << wxT(" ");
            }
            stream << wxT(">\n");
            break;
        }
    case wxTTSSimpleHtmlTag_Close:
        {
            stream << wxT("</") << m_name << wxT(">\n");
            break;
        }
    default:
        {
            break;
        }
    }
    wxTTSSimpleHtmlTag* tag = m_children;
    while (tag)
    {
        tag->Write(stream);
        tag = tag->m_next;
    }

}

void wxTTSSimpleHtmlAttribute::Write(wxOutputStream& stream)
{
    if (m_value.IsEmpty())
        stream << m_name;
    else
    {
        stream << m_name;
        stream << wxT("=\"");
        stream << m_value;
        stream << wxT("\"");
    }
}
